# -*- coding: utf-8 -*-
from __future__ import division, unicode_literals

from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
from django.db.models.query import QuerySet


# 缓存大表的查询中的计数
class CacheCountQuerySet(QuerySet):
    def count(self):
        if self._result_cache is not None:
            return len(self._result_cache)

        # 查询dataplus中的缓存计数表
        from wlmodels.dataplus.models import ELCount
        the_count = ELCount.objects.filter(table=self.model._meta.db_table).first()
        if the_count:
            return the_count.count

        return self.query.get_count(using=self.db)


class UnorderedChangeList(ChangeList):
    def get_ordering(self, request, queryset):
        the_order = super(UnorderedChangeList, self).get_ordering(request, queryset)
        # 只允许对entid进行排序
        if "entid" in the_order:
            return ["entid", ]
        elif "-entid" in the_order:
            return ["-entid", ]
        return []


# 缓存大表的count的admin类
class ELBaseAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return UnorderedChangeList

    def get_queryset(self, request):
        qs = self.model._default_manager.get_queryset()
        qs = qs._clone(klass=CacheCountQuerySet)
        return qs


# 夸库关联企业id的admin类
class EntIdableAdmin(ELBaseAdmin):
    search_fields = ["entid_id", ]

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(EntIdableAdmin, self).get_search_results(request, queryset, search_term)
        if search_term:
            from wlmodels.company.models import ELPost
            the_coms = ELPost.objects.filter(ENTNAME__istartswith=search_term).values_list("entid", flat=True)[:300]
            queryset = self.model.objects.filter(entid_id__in=list(the_coms))
        return queryset, use_distinct
